package com.xgkj.diyiketang.activity.data;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xgkj.diyiketang.activity.BaseActivity;
import com.xgkj.diyiketang.activity.BendiFoodListActivity;
import com.xgkj.diyiketang.activity.SellerListActivity;
import com.xgkj.diyiketang.data.FoodInfo;
import com.xgkj.diyiketang.data.SellerInfo;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by XCKJ_Paladowow on 2016/3/17.
 */
public class MiShiAdapter extends BaseAdapter {
    private Context mContext;
    private List<SellerInfo> bmList = new ArrayList<SellerInfo>();
    GridView gridView;
    private TextView bendiMore;
    private RelativeLayout benditop;
    private List<FoodInfo> foodlist = new ArrayList<FoodInfo>();
    // DisplayMetrics dm;
    private int NUM = 4; // 每行显示个数

    private int LIEWIDTH;//每列宽度
    private int LIE = 10;//列数
    int width;
    MyGridViewAdapter adapter;
    private String areaName;
    private String areaId;
    private ArrayList<GridView> gridViewList;
    ViewPager viewPager;

    public void addFoodList(List<FoodInfo> flist) {
        foodlist.clear();
        foodlist.addAll(flist);

    }

    public String getAreaId() {
        return areaId;
    }

    public void setAreaId(String areaId) {
        this.areaId = areaId;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }
    public MiShiAdapter(Context context) {
        mContext = context;
    }

    public void updateData(List<SellerInfo> list){
        if(bmList != null){
            bmList.addAll(list);
        }
        notifyDataSetChanged();
    }

    public void clearData(){
        if(bmList != null){
            bmList.clear();
        }
        notifyDataSetChanged();
    }


    @Override
    public int getCount() {
        if(bmList != null){
            return bmList.size()+1;
        }
        return 0;
    }
    @Override
    public Object getItem(int position) {
        if(bmList != null){
            return bmList.get(position-1);
        }
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stud
        if(position == 0){
           /* convertView = LayoutInflater.from(this.mContext).inflate(R.layout.gridviewzuoyou, parent, false);
            gridView = (GridView) convertView.findViewById(R.id.gridView1);
            benditop = (RelativeLayout) convertView.findViewById(R.id.bendi_top);
            if (foodlist == null || foodlist.size() == 0) {
                benditop.setVisibility(View.GONE);
                gridView.setVisibility(View.GONE);
                return convertView;
            }
            bendiMore = (TextView) convertView.findViewById(R.id.bendi_more);
            areaName = EatShowSetting.getInstance(mContext).getLocal();
            areaId = getAreaId();
            // PalLog.e("adapter位置",areaName);
            bendiMore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, BendiFoodListActivity.class);
                    intent.putExtra("AreaName", areaName);
                    mContext.startActivity(intent);
                }
            });



            gridView.setOverScrollMode(View.OVER_SCROLL_NEVER);
            getScreenDen();
            LIEWIDTH = width / NUM;
            setValue();

            return convertView;*/

            convertView = LayoutInflater.from(this.mContext).inflate(R.layout.zuoyou_viewpager, parent, false);
            viewPager = (ViewPager) convertView.findViewById(R.id.viewpager);
            benditop = (RelativeLayout) convertView.findViewById(R.id.bendi_top);
            if (foodlist == null || foodlist.size() == 0) {
                benditop.setVisibility(View.GONE);
                viewPager.setVisibility(View.GONE);
                return convertView;
            }else {
                benditop.setVisibility(View.VISIBLE);
                viewPager.setVisibility(View.VISIBLE);
            }
            bendiMore = (TextView) convertView.findViewById(R.id.bendi_more);
            areaName = EatShowSetting.getInstance(mContext).getLocal();
            areaId = getAreaId();
            bendiMore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, BendiFoodListActivity.class);
                    intent.putExtra("AreaName", areaName);
                    mContext.startActivity(intent);
                }
            });



            initPagerView();
            viewPager.setAdapter(new MyPagerAdapter(gridViewList));

            return convertView;

        }
        ChildHolder holder;
        if (null == convertView || convertView.getTag()==null) {
            holder = new ChildHolder();
            convertView = LayoutInflater.from(mContext).inflate(
                    R.layout.mishi_item, null);
            holder.businessLogo = (ImageView) convertView.findViewById(R.id.business_logo);
            holder.businessName = (TextView) convertView.findViewById(R.id.huodong_title);
            holder.pingfen = (RatingBar) convertView.findViewById(R.id.ratingbar_mishi);
            holder.caixi = (TextView) convertView.findViewById(R.id.huodong_caixi);
            holder.renjun = (TextView) convertView.findViewById(R.id.huodong_renjun);
            convertView.setTag(holder);
        } else {
            holder = (ChildHolder) convertView.getTag();
        }

        SellerInfo finfo = bmList.get(position-1);
        if(finfo!=null){
            String foodlogo = finfo.getBusinessLogo();
            if(foodlogo != null && foodlogo.length()>0){
                ViewUtil.Size size =ViewUtil.getImageSize(mContext,R.drawable.default_big_image);
                Bitmap cacheBitmap = ImageCache.getInstance(mContext).getBitmapFromMemoryCache(ImageCache.getInstance(mContext).getCacheKey(foodlogo,size));
                if ( cacheBitmap != null){
                    holder.businessLogo.setImageBitmap(cacheBitmap);
                }else {
                    holder.businessLogo.setImageResource(R.drawable.zhanweitu);
                    ImageCache.getInstance(mContext).loadBitmapToView(holder.businessLogo, foodlogo, size);
                }
            }else {
                holder.businessLogo.setImageResource(R.drawable.zhanweitu);
            }
            holder.businessName.setText(finfo.getBusinessName());
            if(!TextUtils.isEmpty(finfo.getBusinessScore())&&!finfo.getBusinessScore().equals("null")){
                holder.pingfen.setRating(Float.parseFloat(finfo.getBusinessScore()));
            }

//            holder.pingfen.setRating(Float.parseFloat(finfo.getBusinessScore()));
            holder.caixi.setText(finfo.getBusinessType());
            if(finfo.getAverageSpend()!=null){
                holder.renjun.setText("人均￥" + finfo.getAverageSpend());
            }else {
                holder.renjun.setText("人均￥0");
            }


        }
        return convertView;
    }

    class ChildHolder{
        ImageView businessLogo;
        TextView businessName;
        RatingBar pingfen;
        TextView renjun;
        TextView caixi;


    }

    private void setValue() {
        adapter = new MyGridViewAdapter(mContext, LIE);
        adapter.setAreaId(areaId);
        gridView.setAdapter(adapter);
        adapter.updateData(foodlist);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(adapter.getCount() * LIEWIDTH,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        gridView.setLayoutParams(params);
        int count = adapter.getCount();
        gridView.setNumColumns(count);


    }

    private void getScreenDen() {
        DisplayMetrics dm = new DisplayMetrics();
        ((BaseActivity) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);
        width = dm.widthPixels;
    }

    class MyPagerAdapter extends PagerAdapter {
        private ArrayList<GridView> views = new ArrayList<GridView>();
        public MyPagerAdapter(ArrayList<GridView> l) {
            views = l;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(views.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(views.get(position),0);
            return views.get(position);
        }

        @Override
        public int getCount() {
            return views.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view ==object;
        }
    }

    class GridChild{
        ImageView foodIcon;
        TextView foodName;
        TextView foodDesc;
    }


    class GridAdapter extends BaseAdapter{
        ArrayList<FoodInfo> list = new ArrayList<FoodInfo>();

        public GridAdapter(ArrayList<FoodInfo> list) {
            this.list = list;
        }

        public GridAdapter() {
        }

        public void updateData(ArrayList<FoodInfo> arrayList){
            list = arrayList;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            if (list != null &&list.size()>0) {
                return list.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            if (list!=null &&list.size()>0) {
                return list.get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            GridChild gridChild = new GridChild();
            if (convertView == null || convertView.getTag() == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.bendi_item, parent,false);
                gridChild.foodIcon = (ImageView) convertView.findViewById(R.id.food_icon);
                gridChild.foodName = (TextView) convertView.findViewById(R.id.food_name);
                gridChild.foodDesc = (TextView) convertView.findViewById(R.id.food_desc);
                convertView.setTag(gridChild);
            }else {
                gridChild = (GridChild) convertView.getTag();
            }

            FoodInfo info = null;
            if (position <list.size()) {
                info = list.get(position);
            }
            if (info != null){
                if (info.getfoodLogo() != null && info.getfoodLogo().length()!=0){
                    ImageCache.getInstance(mContext).loadBitmapToView(gridChild.foodIcon,info.getfoodLogo(),new ViewUtil.Size(ViewUtil.dip2px(mContext,60),ViewUtil.dip2px(mContext,60)));
                }
                gridChild.foodName.setText(info.getfoodName());
            }

            return convertView;


        }
    }

    private ArrayList<GridView> initPagerView(){
        List<ArrayList<FoodInfo>> dataList = new ArrayList<ArrayList<FoodInfo>>();
        ArrayList<FoodInfo> slist = new ArrayList<FoodInfo>();
        for (int i=0;i<foodlist.size();i++){
            slist.add(foodlist.get(i));
            if ((int)(i+1)%4 ==0 || i==foodlist.size()-1){
                dataList.add(slist);
                slist = new ArrayList<FoodInfo>();
            }
        }
        gridViewList = new ArrayList<GridView>();
        for (int j=0;j<dataList.size();j++) {
            GridView gridView = new GridView(mContext);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            gridView.setLayoutParams(params);
            gridView.setNumColumns(2);
            gridView.setBackgroundColor(mContext.getResources().getColor(R.color.white_bg));
            gridView.setHorizontalSpacing(ViewUtil.dip2px(mContext,10));
            gridView.setVerticalSpacing(ViewUtil.dip2px(mContext,10));
            final GridAdapter adapter = new GridAdapter();
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    FoodInfo fdinfo = (FoodInfo) adapter.getItem(position);
                    String fdid = fdinfo.getfoodId();
                    Intent intent = new Intent(mContext, SellerListActivity.class);
                    intent.putExtra("FOODID", fdid);
                    intent.putExtra("AREAID", areaId);
                    mContext.startActivity(intent);
                }
            });
            gridView.setAdapter(adapter);
            adapter.updateData(dataList.get(j));

//            gridView.setStretchMode(GridView.STRETCH_SPACING);
            gridViewList.add(gridView);
        }

        return gridViewList;

    }
}
